import copy
import datetime
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from MedicineReminder.models import ReminderItem, FinishedRecord
from SecureHelperServer.settings import formatResponseData
from utils.conf import verifyID, Response
from utils.custom import MyJWTAuthentication


class CancelFinishedRecord(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = [MyJWTAuthentication]
    # 局部(本视图有效)权限类
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        """
        取消服药记录
        """
        data = copy.deepcopy(formatResponseData)
        try:
            nowTimeStamp = request.data.get("nowTimeStamp")
            remindItemId = request.data.get("remindItemId")

            if not (nowTimeStamp and remindItemId):
                return Response(data=data, responseMsg="请求参数缺失", loggerMsg="请求参数缺失", isError=True)

            if not verifyID(remindItemId):
                return Response(data=data, responseMsg="该提醒项不存在",
                                loggerMsg=f"取消服药记录：remindItemId={remindItemId}，不是一个有效的id", isError=True)

            # 查询出对应服药记录范围之内的服药记录
            remindItem = ReminderItem.objects.filter(id=remindItemId, medicine__user=request.user).first()

            if not remindItem:
                return Response(data=data, responseMsg="该提醒项不存在",
                                loggerMsg=f"取消服药记录：未找到对应的remindItem={remindItemId}的提醒项", isError=True)

            nowTimeStampToDateString = datetime.datetime.fromtimestamp(int(nowTimeStamp) // 1000).strftime(
                "%Y-%m-%d")
            finishedRecordList = FinishedRecord.objects.filter(reminderItem=remindItem)

            # 删除同天的服药记录
            for finishedRecord in finishedRecordList:
                finishedRecordTimeStampToDateString = datetime.datetime.fromtimestamp(
                    int(finishedRecord.timeStamp) // 1000).strftime("%Y-%m-%d")
                if finishedRecordTimeStampToDateString == nowTimeStampToDateString:
                    finishedRecord.delete()
                    return Response(data=data, responseMsg="取消成功",
                                    loggerMsg=f"取消服药记录成功: uid={request.user.uid}")

            # 没有找到同天的服药记录
            return Response(data=data, responseMsg="取消失败",
                            loggerMsg=f"取消服药记录：没有找到同天的服药记录, remindItemId={remindItemId}", isError=True)

        except Exception as e:
            return Response(data=data, responseMsg="ServerError",
                            loggerMsg=f"请求处理失败: {e}", isError=True)
